<!DOCTYPE html>
<html lang="en-us">
  <head>

    <meta http-equiv="content-type" content="text/html; charset=utf-8">
    
<meta charset="UTF-8">
<title>Script score query | Elasticsearch Guide [7.7] | Elastic</title>
<link rel="home" href="index.html" title="Elasticsearch Guide [7.7]">
<link rel="up" href="specialized-queries.html" title="Specialized queries">
<link rel="prev" href="query-dsl-script-query.html" title="Script query">
<link rel="next" href="query-dsl-wrapper-query.html" title="Wrapper query">
<meta name="DC.type" content="Learn/Docs/Elasticsearch/Reference/7.7">
<meta name="DC.subject" content="Elasticsearch">
<meta name="DC.identifier" content="7.7">
<meta name="robots" content="noindex,nofollow">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <script src="https://cdn.optimizely.com/js/18132920325.js"></script>
    <link rel="apple-touch-icon" sizes="57x57" href="/apple-icon-57x57.png">
    <link rel="apple-touch-icon" sizes="60x60" href="/apple-icon-60x60.png">
    <link rel="apple-touch-icon" sizes="72x72" href="/apple-icon-72x72.png">
    <link rel="apple-touch-icon" sizes="76x76" href="/apple-icon-76x76.png">
    <link rel="apple-touch-icon" sizes="114x114" href="/apple-icon-114x114.png">
    <link rel="apple-touch-icon" sizes="120x120" href="/apple-icon-120x120.png">
    <link rel="apple-touch-icon" sizes="144x144" href="/apple-icon-144x144.png">
    <link rel="apple-touch-icon" sizes="152x152" href="/apple-icon-152x152.png">
    <link rel="apple-touch-icon" sizes="180x180" href="/apple-icon-180x180.png">
    <link rel="icon" type="image/png" href="/favicon-32x32.png" sizes="32x32">
    <link rel="icon" type="image/png" href="/android-chrome-192x192.png" sizes="192x192">
    <link rel="icon" type="image/png" href="/favicon-96x96.png" sizes="96x96">
    <link rel="icon" type="image/png" href="/favicon-16x16.png" sizes="16x16">
    <link rel="manifest" href="/manifest.json">
    <meta name="apple-mobile-web-app-title" content="Elastic">
    <meta name="application-name" content="Elastic">
    <meta name="msapplication-TileColor" content="#ffffff">
    <meta name="msapplication-TileImage" content="/mstile-144x144.png">
    <meta name="theme-color" content="#ffffff">
    <meta name="naver-site-verification" content="936882c1853b701b3cef3721758d80535413dbfd">
    <meta name="yandex-verification" content="d8a47e95d0972434">
    <meta name="localized" content="true">
    <meta name="st:robots" content="follow,index">
    <meta property="og:image" content="https://www.elastic.co/static/images/elastic-logo-200.png">
    <link rel="shortcut icon" href="/favicon.ico" type="image/x-icon">
    <link rel="icon" href="/favicon.ico" type="image/x-icon">
    <link rel="apple-touch-icon-precomposed" sizes="64x64" href="/favicon_64x64_16bit.png">
    <link rel="apple-touch-icon-precomposed" sizes="32x32" href="/favicon_32x32.png">
    <link rel="apple-touch-icon-precomposed" sizes="16x16" href="/favicon_16x16.png">
    <!-- Give IE8 a fighting chance -->
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->
    <link rel="stylesheet" type="text/css" href="/guide/static/styles.css">
  </head>

  <!--© 2015-2021 Elasticsearch B.V. Copying, publishing and/or distributing without written permission is strictly prohibited.-->

  <body>
    <!-- Google Tag Manager -->
    <script>dataLayer = [];</script><noscript><iframe src="//www.googletagmanager.com/ns.html?id=GTM-58RLH5" height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
    <script>(function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start': new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0], j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src= '//www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f); })(window,document,'script','dataLayer','GTM-58RLH5');</script>
    <!-- End Google Tag Manager -->

    <!-- Global site tag (gtag.js) - Google Analytics -->
    <script async src="https://www.googletagmanager.com/gtag/js?id=UA-12395217-16"></script>
    <script>
      window.dataLayer = window.dataLayer || [];
      function gtag(){dataLayer.push(arguments);}
      gtag('js', new Date());
      gtag('config', 'UA-12395217-16');
    </script>

    <!--BEGIN QUALTRICS WEBSITE FEEDBACK SNIPPET-->
    <script type="text/javascript">
      (function(){var g=function(e,h,f,g){
      this.get=function(a){for(var a=a+"=",c=document.cookie.split(";"),b=0,e=c.length;b<e;b++){for(var d=c[b];" "==d.charAt(0);)d=d.substring(1,d.length);if(0==d.indexOf(a))return d.substring(a.length,d.length)}return null};
      this.set=function(a,c){var b="",b=new Date;b.setTime(b.getTime()+6048E5);b="; expires="+b.toGMTString();document.cookie=a+"="+c+b+"; path=/; "};
      this.check=function(){var a=this.get(f);if(a)a=a.split(":");else if(100!=e)"v"==h&&(e=Math.random()>=e/100?0:100),a=[h,e,0],this.set(f,a.join(":"));else return!0;var c=a[1];if(100==c)return!0;switch(a[0]){case "v":return!1;case "r":return c=a[2]%Math.floor(100/c),a[2]++,this.set(f,a.join(":")),!c}return!0};
      this.go=function(){if(this.check()){var a=document.createElement("script");a.type="text/javascript";a.src=g;document.body&&document.body.appendChild(a)}};
      this.start=function(){var a=this;window.addEventListener?window.addEventListener("load",function(){a.go()},!1):window.attachEvent&&window.attachEvent("onload",function(){a.go()})}};
      try{(new g(100,"r","QSI_S_ZN_emkP0oSe9Qrn7kF","https://znemkp0ose9qrn7kf-elastic.siteintercept.qualtrics.com/WRSiteInterceptEngine/?Q_ZID=ZN_emkP0oSe9Qrn7kF")).start()}catch(i){}})();
    </script><div id="ZN_emkP0oSe9Qrn7kF"><!--DO NOT REMOVE-CONTENTS PLACED HERE--></div>
    <!--END WEBSITE FEEDBACK SNIPPET-->

    <div id="elastic-nav" style="display:none;"></div>
    <script src="https://www.elastic.co/elastic-nav.js"></script>

    <!-- Subnav -->
    <div>
      <div>
        <div class="tertiary-nav d-none d-md-block">
          <div class="container">
            <div class="p-t-b-15 d-flex justify-content-between nav-container">
              <div class="breadcrum-wrapper"><span><a href="/guide/" style="font-size: 14px; font-weight: 600; color: #000;">Docs</a></span></div>
            </div>
          </div>
        </div>
      </div>
    </div>

    <div class="main-container">
      <section id="content">
        <div class="content-wrapper">

          <section id="guide" lang="en">
            <div class="container">
              <div class="row">
                <div class="col-xs-12 col-sm-8 col-md-8 guide-section">
                  <!-- start body -->
                  <div class="page_header">
<strong>IMPORTANT</strong>: No additional bug fixes or documentation updates
will be released for this version. For the latest information, see the
<a href="../current/index.html">current release documentation</a>.
</div>
<div id="content">
<div class="breadcrumbs">
<span class="breadcrumb-link"><a href="index.html">Elasticsearch Guide [7.7]</a></span>
»
<span class="breadcrumb-link"><a href="query-dsl.html">Query DSL</a></span>
»
<span class="breadcrumb-link"><a href="specialized-queries.html">Specialized queries</a></span>
»
<span class="breadcrumb-node">Script score query</span>
</div>
<div class="navheader">
<span class="prev">
<a href="query-dsl-script-query.html">« Script query</a>
</span>
<span class="next">
<a href="query-dsl-wrapper-query.html">Wrapper query »</a>
</span>
</div>
<div class="section">
<div class="titlepage"><div><div>
<h2 class="title">
<a id="query-dsl-script-score-query"></a>Script score query<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/query-dsl/script-score-query.asciidoc">edit</a>
</h2>
</div></div></div>

<p>Uses a <a class="xref" href="modules-scripting.html" title="Scripting">script</a> to provide a custom score for returned
documents.</p>
<p>The <code class="literal">script_score</code> query is useful if, for example, a scoring function is expensive and you only need to calculate the score of a filtered set of documents.</p>
<div class="section">
<div class="titlepage"><div><div>
<h3 class="title">
<a id="script-score-query-ex-request"></a>Example request<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/query-dsl/script-score-query.asciidoc">edit</a>
</h3>
</div></div></div>
<p>The following <code class="literal">script_score</code> query assigns each returned document a score equal to the <code class="literal">likes</code> field value divided by <code class="literal">10</code>.</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">GET /_search
{
    "query" : {
        "script_score" : {
            "query" : {
                "match": { "message": "elasticsearch" }
            },
            "script" : {
                "source" : "doc['likes'].value / 10 "
            }
        }
     }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/260.console"></div>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h3 class="title">
<a id="script-score-top-level-params"></a>Top-level parameters for <code class="literal">script_score</code><a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/query-dsl/script-score-query.asciidoc">edit</a>
</h3>
</div></div></div>
<div class="variablelist">
<dl class="variablelist">
<dt>
<span class="term">
<code class="literal">query</code>
</span>
</dt>
<dd>
(Required, query object) Query used to return documents.
</dd>
<dt>
<span class="term">
<code class="literal">script</code>
</span>
</dt>
<dd>
<p>(Required, <a class="xref" href="modules-scripting-using.html" title="How to use scripts">script object</a>) Script used to compute the score of documents returned by the <code class="literal">query</code>.</p>
<div class="important admon">
<div class="icon"></div>
<div class="admon_content">
<p>Final relevance scores from the <code class="literal">script_score</code> query cannot be
negative. To support certain search optimizations, Lucene requires
scores be positive or <code class="literal">0</code>.</p>
</div>
</div>
</dd>
<dt>
<span class="term">
<code class="literal">min_score</code>
</span>
</dt>
<dd>
(Optional, float) Documents with a score lower
than this floating point number are excluded from the search results.
</dd>
<dt>
<span class="term">
<code class="literal">boost</code>
</span>
</dt>
<dd>
(Optional, float) Documents' scores produced by <code class="literal">script</code> are
multiplied by <code class="literal">boost</code> to produce final documents' scores. Defaults to <code class="literal">1.0</code>.
</dd>
</dl>
</div>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h3 class="title">
<a id="script-score-query-notes"></a>Notes<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/query-dsl/script-score-query.asciidoc">edit</a>
</h3>
</div></div></div>
<div class="section">
<div class="titlepage"><div><div>
<h4 class="title">
<a id="script-score-access-scores"></a>Use relevance scores in a script<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/query-dsl/script-score-query.asciidoc">edit</a>
</h4>
</div></div></div>
<p>Within a script, you can
<a href="/guide/en/elasticsearch/reference/7.7/modules-scripting-fields.html#scripting-score" class="ulink" target="_top">access</a>
the <code class="literal">_score</code> variable which represents the current relevance score of a
document.</p>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h4 class="title">
<a id="script-score-predefined-functions"></a>Predefined functions<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/query-dsl/script-score-query.asciidoc">edit</a>
</h4>
</div></div></div>
<p>You can use any of the available <a href="/guide/en/elasticsearch/painless/7.7/painless-contexts.html" class="ulink" target="_top">painless
functions</a> in your <code class="literal">script</code>. You can also use the following predefined functions
to customize scoring:</p>
<div class="ulist itemizedlist">
<ul class="itemizedlist">
<li class="listitem">
<a class="xref" href="query-dsl-script-score-query.html#script-score-saturation" title="Saturation">Saturation</a>
</li>
<li class="listitem">
<a class="xref" href="query-dsl-script-score-query.html#script-score-sigmoid" title="Sigmoid">Sigmoid</a>
</li>
<li class="listitem">
<a class="xref" href="query-dsl-script-score-query.html#random-score-function" title="Random score function">Random score function</a>
</li>
<li class="listitem">
<a class="xref" href="query-dsl-script-score-query.html#decay-functions-numeric-fields" title="Decay functions for numeric fields">Decay functions for numeric fields</a>
</li>
<li class="listitem">
<a class="xref" href="query-dsl-script-score-query.html#decay-functions-geo-fields" title="Decay functions for geo fields">Decay functions for geo fields</a>
</li>
<li class="listitem">
<a class="xref" href="query-dsl-script-score-query.html#decay-functions-date-fields" title="Decay functions for date fields">Decay functions for date fields</a>
</li>
<li class="listitem">
<a class="xref" href="query-dsl-script-score-query.html#script-score-functions-vector-fields" title="Functions for vector fields">Functions for vector fields</a>
</li>
</ul>
</div>
<p>We suggest using these predefined functions instead of writing your own.
These functions take advantage of efficiencies from Elasticsearch' internal mechanisms.</p>
<div class="section">
<div class="titlepage"><div><div>
<h5 class="title">
<a id="script-score-saturation"></a>Saturation<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/query-dsl/script-score-query.asciidoc">edit</a>
</h5>
</div></div></div>
<p><code class="literal">saturation(value,k) = value/(k + value)</code></p>
<div class="pre_wrapper lang-js">
<pre class="programlisting prettyprint lang-js">"script" : {
    "source" : "saturation(doc['likes'].value, 1)"
}</pre>
</div>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h5 class="title">
<a id="script-score-sigmoid"></a>Sigmoid<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/query-dsl/script-score-query.asciidoc">edit</a>
</h5>
</div></div></div>
<p><code class="literal">sigmoid(value, k, a) = value^a/ (k^a + value^a)</code></p>
<div class="pre_wrapper lang-js">
<pre class="programlisting prettyprint lang-js">"script" : {
    "source" : "sigmoid(doc['likes'].value, 2, 1)"
}</pre>
</div>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h5 class="title">
<a id="random-score-function"></a>Random score function<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/query-dsl/script-score-query.asciidoc">edit</a>
</h5>
</div></div></div>
<p><code class="literal">random_score</code> function generates scores that are uniformly distributed
from 0 up to but not including 1.</p>
<p><code class="literal">randomScore</code> function has the following syntax:
<code class="literal">randomScore(&lt;seed&gt;, &lt;fieldName&gt;)</code>.
It has a required parameter - <code class="literal">seed</code> as an integer value,
and an optional parameter - <code class="literal">fieldName</code> as a string value.</p>
<div class="pre_wrapper lang-js">
<pre class="programlisting prettyprint lang-js">"script" : {
    "source" : "randomScore(100, '_seq_no')"
}</pre>
</div>
<p>If the <code class="literal">fieldName</code> parameter is omitted, the internal Lucene
document ids will be used as a source of randomness. This is very efficient,
but unfortunately not reproducible since documents might be renumbered
by merges.</p>
<div class="pre_wrapper lang-js">
<pre class="programlisting prettyprint lang-js">"script" : {
    "source" : "randomScore(100)"
}</pre>
</div>
<p>Note that documents that are within the same shard and have the
same value for field will get the same score, so it is usually desirable
to use a field that has unique values for all documents across a shard.
A good default choice might be to use the <code class="literal">_seq_no</code>
field, whose only drawback is that scores will change if the document is
updated since update operations also update the value of the <code class="literal">_seq_no</code> field.</p>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h5 class="title">
<a id="decay-functions-numeric-fields"></a>Decay functions for numeric fields<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/query-dsl/script-score-query.asciidoc">edit</a>
</h5>
</div></div></div>
<p>You can read more about decay functions
<a href="/guide/en/elasticsearch/reference/7.7/query-dsl-function-score-query.html#function-decay" class="ulink" target="_top">here</a>.</p>
<div class="ulist itemizedlist">
<ul class="itemizedlist">
<li class="listitem">
<code class="literal">double decayNumericLinear(double origin, double scale, double offset, double decay, double docValue)</code>
</li>
<li class="listitem">
<code class="literal">double decayNumericExp(double origin, double scale, double offset, double decay, double docValue)</code>
</li>
<li class="listitem">
<code class="literal">double decayNumericGauss(double origin, double scale, double offset, double decay, double docValue)</code>
</li>
</ul>
</div>
<div class="pre_wrapper lang-js">
<pre class="programlisting prettyprint lang-js">"script" : {
    "source" : "decayNumericLinear(params.origin, params.scale, params.offset, params.decay, doc['dval'].value)",
    "params": { <a id="CO58-1"></a><i class="conum" data-value="1"></i>
        "origin": 20,
        "scale": 10,
        "decay" : 0.5,
        "offset" : 0
    }
}</pre>
</div>
<div class="calloutlist">
<table border="0" summary="Callout list">
<tr>
<td align="left" valign="top" width="5%">
<p><a href="#CO58-1"><i class="conum" data-value="1"></i></a></p>
</td>
<td align="left" valign="top">
<p>Using <code class="literal">params</code> allows to compile the script only once, even if params change.</p>
</td>
</tr>
</table>
</div>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h5 class="title">
<a id="decay-functions-geo-fields"></a>Decay functions for geo fields<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/query-dsl/script-score-query.asciidoc">edit</a>
</h5>
</div></div></div>
<div class="ulist itemizedlist">
<ul class="itemizedlist">
<li class="listitem">
<code class="literal">double decayGeoLinear(String originStr, String scaleStr, String offsetStr, double decay, GeoPoint docValue)</code>
</li>
<li class="listitem">
<code class="literal">double decayGeoExp(String originStr, String scaleStr, String offsetStr, double decay, GeoPoint docValue)</code>
</li>
<li class="listitem">
<code class="literal">double decayGeoGauss(String originStr, String scaleStr, String offsetStr, double decay, GeoPoint docValue)</code>
</li>
</ul>
</div>
<div class="pre_wrapper lang-js">
<pre class="programlisting prettyprint lang-js">"script" : {
    "source" : "decayGeoExp(params.origin, params.scale, params.offset, params.decay, doc['location'].value)",
    "params": {
        "origin": "40, -70.12",
        "scale": "200km",
        "offset": "0km",
        "decay" : 0.2
    }
}</pre>
</div>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h5 class="title">
<a id="decay-functions-date-fields"></a>Decay functions for date fields<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/query-dsl/script-score-query.asciidoc">edit</a>
</h5>
</div></div></div>
<div class="ulist itemizedlist">
<ul class="itemizedlist">
<li class="listitem">
<code class="literal">double decayDateLinear(String originStr, String scaleStr, String offsetStr, double decay, JodaCompatibleZonedDateTime docValueDate)</code>
</li>
<li class="listitem">
<code class="literal">double decayDateExp(String originStr, String scaleStr, String offsetStr, double decay, JodaCompatibleZonedDateTime docValueDate)</code>
</li>
<li class="listitem">
<code class="literal">double decayDateGauss(String originStr, String scaleStr, String offsetStr, double decay, JodaCompatibleZonedDateTime docValueDate)</code>
</li>
</ul>
</div>
<div class="pre_wrapper lang-js">
<pre class="programlisting prettyprint lang-js">"script" : {
    "source" : "decayDateGauss(params.origin, params.scale, params.offset, params.decay, doc['date'].value)",
    "params": {
        "origin": "2008-01-01T01:00:00Z",
        "scale": "1h",
        "offset" : "0",
        "decay" : 0.5
    }
}</pre>
</div>
<div class="note admon">
<div class="icon"></div>
<div class="admon_content">
<p>Decay functions on dates are limited to dates in the default format
and default time zone. Also calculations with <code class="literal">now</code> are not supported.</p>
</div>
</div>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h5 class="title">
<a id="script-score-functions-vector-fields"></a>Functions for vector fields<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/query-dsl/script-score-query.asciidoc">edit</a>
</h5>
</div></div></div>
<p><a class="xref" href="query-dsl-script-score-query.html#vector-functions" title="Functions for vector fields">Functions for vector fields</a> are accessible through
<code class="literal">script_score</code> query.</p>
</div>

</div>

<div class="section">
<div class="titlepage"><div><div>
<h4 class="title">
<a id="_allow_expensive_queries_5"></a>Allow expensive queries<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/query-dsl/script-score-query.asciidoc">edit</a>
</h4>
</div></div></div>
<p>Script score queries will not be executed if <a class="xref" href="query-dsl.html#query-dsl-allow-expensive-queries"><code class="literal">search.allow_expensive_queries</code></a>
is set to false.</p>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h4 class="title">
<a id="script-score-faster-alt"></a>Faster alternatives<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/query-dsl/script-score-query.asciidoc">edit</a>
</h4>
</div></div></div>
<p>The <code class="literal">script_score</code> query calculates the score for
every matching document, or hit. There are faster alternative query types that
can efficiently skip non-competitive hits:</p>
<div class="ulist itemizedlist">
<ul class="itemizedlist">
<li class="listitem">
If you want to boost documents on some static fields, use the
<a class="xref" href="query-dsl-rank-feature-query.html" title="Rank feature query"><code class="literal">rank_feature</code></a> query.
</li>
<li class="listitem">
If you want to boost documents closer to a date or geographic point, use the
<a class="xref" href="query-dsl-distance-feature-query.html" title="Distance feature query"><code class="literal">distance_feature</code></a> query.
</li>
</ul>
</div>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h4 class="title">
<a id="script-score-function-score-transition"></a>Transition from the function score query<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/query-dsl/script-score-query.asciidoc">edit</a>
</h4>
</div></div></div>
<p>We are deprecating the <a class="xref" href="query-dsl-function-score-query.html" title="Function score query"><code class="literal">function_score</code></a>
query. We recommend using the <code class="literal">script_score</code> query instead.</p>
<p>You can implement the following functions from the <code class="literal">function_score</code> query using
the <code class="literal">script_score</code> query:</p>
<div class="ulist itemizedlist">
<ul class="itemizedlist">
<li class="listitem">
<a class="xref" href="query-dsl-script-score-query.html#script-score" title="script_score"><code class="literal">script_score</code></a>
</li>
<li class="listitem">
<a class="xref" href="query-dsl-script-score-query.html#weight" title="weight"><code class="literal">weight</code></a>
</li>
<li class="listitem">
<a class="xref" href="query-dsl-script-score-query.html#random-score" title="random_score"><code class="literal">random_score</code></a>
</li>
<li class="listitem">
<a class="xref" href="query-dsl-script-score-query.html#field-value-factor" title="field_value_factor"><code class="literal">field_value_factor</code></a>
</li>
<li class="listitem">
<a class="xref" href="query-dsl-script-score-query.html#decay-functions" title="decay functions"><code class="literal">decay</code> functions</a>
</li>
</ul>
</div>
<div class="section">
<div class="titlepage"><div><div>
<h5 class="title">
<a id="script-score"></a><code class="literal">script_score</code><a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/query-dsl/script-score-query.asciidoc">edit</a>
</h5>
</div></div></div>
<p>What you used in <code class="literal">script_score</code> of the Function Score query, you
can copy into the Script Score query. No changes here.</p>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h5 class="title">
<a id="weight"></a><code class="literal">weight</code><a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/query-dsl/script-score-query.asciidoc">edit</a>
</h5>
</div></div></div>
<p><code class="literal">weight</code> function can be implemented in the Script Score query through
the following script:</p>
<div class="pre_wrapper lang-js">
<pre class="programlisting prettyprint lang-js">"script" : {
    "source" : "params.weight * _score",
    "params": {
        "weight": 2
    }
}</pre>
</div>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h5 class="title">
<a id="random-score"></a><code class="literal">random_score</code><a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/query-dsl/script-score-query.asciidoc">edit</a>
</h5>
</div></div></div>
<p>Use <code class="literal">randomScore</code> function
as described in <a class="xref" href="query-dsl-script-score-query.html#random-score-function" title="Random score function">random score function</a>.</p>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h5 class="title">
<a id="field-value-factor"></a><code class="literal">field_value_factor</code><a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/query-dsl/script-score-query.asciidoc">edit</a>
</h5>
</div></div></div>
<p><code class="literal">field_value_factor</code> function can be easily implemented through script:</p>
<div class="pre_wrapper lang-js">
<pre class="programlisting prettyprint lang-js">"script" : {
    "source" : "Math.log10(doc['field'].value * params.factor)",
    "params" : {
        "factor" : 5
    }
}</pre>
</div>
<p>For checking if a document has a missing value, you can use
<code class="literal">doc['field'].size() == 0</code>. For example, this script will use
a value <code class="literal">1</code> if a document doesn’t have a field <code class="literal">field</code>:</p>
<div class="pre_wrapper lang-js">
<pre class="programlisting prettyprint lang-js">"script" : {
    "source" : "Math.log10((doc['field'].size() == 0 ? 1 : doc['field'].value()) * params.factor)",
    "params" : {
        "factor" : 5
    }
}</pre>
</div>
<p>This table lists how <code class="literal">field_value_factor</code> modifiers can be implemented
through a script:</p>
<div class="informaltable">
<table border="1" cellpadding="4px">
<colgroup>
<col class="col_1">
<col class="col_2">
</colgroup>
<thead>
<tr>
<th align="left" valign="top">Modifier</th>
<th align="left" valign="top">Implementation in Script Score</th>
</tr>
</thead>
<tbody>
<tr>
<td align="left" valign="top"><p><code class="literal">none</code></p></td>
<td align="left" valign="top"><p>-</p></td>
</tr>
<tr>
<td align="left" valign="top"><p><code class="literal">log</code></p></td>
<td align="left" valign="top"><p><code class="literal">Math.log10(doc['f'].value)</code></p></td>
</tr>
<tr>
<td align="left" valign="top"><p><code class="literal">log1p</code></p></td>
<td align="left" valign="top"><p><code class="literal">Math.log10(doc['f'].value + 1)</code></p></td>
</tr>
<tr>
<td align="left" valign="top"><p><code class="literal">log2p</code></p></td>
<td align="left" valign="top"><p><code class="literal">Math.log10(doc['f'].value + 2)</code></p></td>
</tr>
<tr>
<td align="left" valign="top"><p><code class="literal">ln</code></p></td>
<td align="left" valign="top"><p><code class="literal">Math.log(doc['f'].value)</code></p></td>
</tr>
<tr>
<td align="left" valign="top"><p><code class="literal">ln1p</code></p></td>
<td align="left" valign="top"><p><code class="literal">Math.log(doc['f'].value + 1)</code></p></td>
</tr>
<tr>
<td align="left" valign="top"><p><code class="literal">ln2p</code></p></td>
<td align="left" valign="top"><p><code class="literal">Math.log(doc['f'].value + 2)</code></p></td>
</tr>
<tr>
<td align="left" valign="top"><p><code class="literal">square</code></p></td>
<td align="left" valign="top"><p><code class="literal">Math.pow(doc['f'].value, 2)</code></p></td>
</tr>
<tr>
<td align="left" valign="top"><p><code class="literal">sqrt</code></p></td>
<td align="left" valign="top"><p><code class="literal">Math.sqrt(doc['f'].value)</code></p></td>
</tr>
<tr>
<td align="left" valign="top"><p><code class="literal">reciprocal</code></p></td>
<td align="left" valign="top"><p><code class="literal">1.0 / doc['f'].value</code></p></td>
</tr>
</tbody>
</table>
</div>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h5 class="title">
<a id="decay-functions"></a><code class="literal">decay</code> functions<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/query-dsl/script-score-query.asciidoc">edit</a>
</h5>
</div></div></div>
<p>The <code class="literal">script_score</code> query has equivalent <a class="xref" href="query-dsl-script-score-query.html#decay-functions" title="decay functions">decay functions</a>
that can be used in script.</p>
</div>

</div>

<div class="section xpack">
<div class="titlepage"><div><div>
<h4 class="title">
<a id="vector-functions"></a>Functions for vector fields<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/vectors/vector-functions.asciidoc">edit</a><a class="xpack_tag" href="/subscriptions"></a>
</h4>
</div></div></div>
<div class="note admon">
<div class="icon"></div>
<div class="admon_content">
<p>During vector functions' calculation, all matched documents are
linearly scanned. Thus, expect the query time grow linearly
with the number of matched documents. For this reason, we recommend
to limit the number of matched documents with a <code class="literal">query</code> parameter.</p>
</div>
</div>
<div class="section">
<div class="titlepage"><div><div>
<h5 class="title">
<a id="_dense_vector_functions"></a><code class="literal">dense_vector</code> functions<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/vectors/vector-functions.asciidoc">edit</a>
</h5>
</div></div></div>
<p>Let’s create an index with a <code class="literal">dense_vector</code> mapping and index a couple
of documents into it.</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">PUT my_index
{
  "mappings": {
    "properties": {
      "my_dense_vector": {
        "type": "dense_vector",
        "dims": 3
      },
      "status" : {
        "type" : "keyword"
      }
    }
  }
}

PUT my_index/_doc/1
{
  "my_dense_vector": [0.5, 10, 6],
  "status" : "published"
}

PUT my_index/_doc/2
{
  "my_dense_vector": [-0.5, 10, 10],
  "status" : "published"
}

POST my_index/_refresh</pre>
</div>
<div class="console_widget" data-snippet="snippets/261.console"></div>
<p>The <code class="literal">cosineSimilarity</code> function calculates the measure of
cosine similarity between a given query vector and document vectors.</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">GET my_index/_search
{
  "query": {
    "script_score": {
      "query" : {
        "bool" : {
          "filter" : {
            "term" : {
              "status" : "published" <a id="CO59-1"></a><i class="conum" data-value="1"></i>
            }
          }
        }
      },
      "script": {
        "source": "cosineSimilarity(params.query_vector, 'my_dense_vector') + 1.0", <a id="CO59-2"></a><i class="conum" data-value="2"></i>
        "params": {
          "query_vector": [4, 3.4, -0.2]  <a id="CO59-3"></a><i class="conum" data-value="3"></i>
        }
      }
    }
  }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/262.console"></div>
<div class="calloutlist">
<table border="0" summary="Callout list">
<tr>
<td align="left" valign="top" width="5%">
<p><a href="#CO59-1"><i class="conum" data-value="1"></i></a></p>
</td>
<td align="left" valign="top">
<p>To restrict the number of documents on which script score calculation is applied, provide a filter.</p>
</td>
</tr>
<tr>
<td align="left" valign="top" width="5%">
<p><a href="#CO59-2"><i class="conum" data-value="2"></i></a></p>
</td>
<td align="left" valign="top">
<p>The script adds 1.0 to the cosine similarity to prevent the score from being negative.</p>
</td>
</tr>
<tr>
<td align="left" valign="top" width="5%">
<p><a href="#CO59-3"><i class="conum" data-value="3"></i></a></p>
</td>
<td align="left" valign="top">
<p>To take advantage of the script optimizations, provide a query vector as a script parameter.</p>
</td>
</tr>
</table>
</div>
<div class="note admon">
<div class="icon"></div>
<div class="admon_content">
<p>If a document’s dense vector field has a number of dimensions
different from the query’s vector, an error will be thrown.</p>
</div>
</div>
<p>The <code class="literal">dotProduct</code> function calculates the measure of
dot product between a given query vector and document vectors.</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">GET my_index/_search
{
  "query": {
    "script_score": {
      "query" : {
        "bool" : {
          "filter" : {
            "term" : {
              "status" : "published"
            }
          }
        }
      },
      "script": {
        "source": """
          double value = dotProduct(params.query_vector, 'my_dense_vector');
          return sigmoid(1, Math.E, -value); <a id="CO60-1"></a><i class="conum" data-value="1"></i>
        """,
        "params": {
          "query_vector": [4, 3.4, -0.2]
        }
      }
    }
  }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/263.console"></div>
<div class="calloutlist">
<table border="0" summary="Callout list">
<tr>
<td align="left" valign="top" width="5%">
<p><a href="#CO60-1"><i class="conum" data-value="1"></i></a></p>
</td>
<td align="left" valign="top">
<p>Using the standard sigmoid function prevents scores from being negative.</p>
</td>
</tr>
</table>
</div>
<p>The <code class="literal">l1norm</code> function calculates L<sup>1</sup> distance
(Manhattan distance) between a given query vector and
document vectors.</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">GET my_index/_search
{
  "query": {
    "script_score": {
      "query" : {
        "bool" : {
          "filter" : {
            "term" : {
              "status" : "published"
            }
          }
        }
      },
      "script": {
        "source": "1 / (1 + l1norm(params.queryVector, 'my_dense_vector'))", <a id="CO61-1"></a><i class="conum" data-value="1"></i>
        "params": {
          "queryVector": [4, 3.4, -0.2]
        }
      }
    }
  }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/264.console"></div>
<div class="calloutlist">
<table border="0" summary="Callout list">
<tr>
<td align="left" valign="top" width="5%">
<p><a href="#CO61-1"><i class="conum" data-value="1"></i></a></p>
</td>
<td align="left" valign="top">
<p>Unlike <code class="literal">cosineSimilarity</code> that represent similarity, <code class="literal">l1norm</code> and
<code class="literal">l2norm</code> shown below represent distances or differences. This means, that
the more similar the vectors are, the lower the scores will be that are
produced by the <code class="literal">l1norm</code> and <code class="literal">l2norm</code> functions.
Thus, as we need more similar vectors to score higher,
we reversed the output from <code class="literal">l1norm</code> and <code class="literal">l2norm</code>. Also, to avoid
division by 0 when a document vector matches the query exactly,
we added <code class="literal">1</code> in the denominator.</p>
</td>
</tr>
</table>
</div>
<p>The <code class="literal">l2norm</code> function calculates L<sup>2</sup> distance
(Euclidean distance) between a given query vector and
document vectors.</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">GET my_index/_search
{
  "query": {
    "script_score": {
      "query" : {
        "bool" : {
          "filter" : {
            "term" : {
              "status" : "published"
            }
          }
        }
      },
      "script": {
        "source": "1 / (1 + l2norm(params.queryVector, 'my_dense_vector'))",
        "params": {
          "queryVector": [4, 3.4, -0.2]
        }
      }
    }
  }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/265.console"></div>
<div class="note admon">
<div class="icon"></div>
<div class="admon_content">
<p>If a document doesn’t have a value for a vector field on which
a vector function is executed, an error will be thrown.</p>
</div>
</div>
<p>You can check if a document has a value for the field <code class="literal">my_vector</code> by
<code class="literal">doc['my_vector'].size() == 0</code>. Your overall script can look like this:</p>
<div class="pre_wrapper lang-js">
<pre class="programlisting prettyprint lang-js">"source": "doc['my_vector'].size() == 0 ? 0 : cosineSimilarity(params.queryVector, 'my_vector')"</pre>
</div>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h5 class="title">
<a id="_sparse_vector_functions"></a><code class="literal">sparse_vector</code> functions<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/vectors/vector-functions.asciidoc">edit</a>
</h5>
</div></div></div>
<div class="warning admon">
<div class="icon"></div>
<div class="admon_content">
<h3>Deprecated in 7.6.</h3>
<p>The <code class="literal">sparse_vector</code> type is deprecated and will be removed in 8.0.</p>
</div>
</div>
<p>Let’s create an index with a <code class="literal">sparse_vector</code> mapping and index a couple
of documents into it.</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">PUT my_sparse_index
{
  "mappings": {
    "properties": {
      "my_sparse_vector": {
        "type": "sparse_vector"
      },
      "status" : {
        "type" : "keyword"
      }
    }
  }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/266.console"></div>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">PUT my_sparse_index/_doc/1
{
  "my_sparse_vector": {"2": 1.5, "15" : 2, "50": -1.1, "4545": 1.1},
  "status" : "published"
}

PUT my_sparse_index/_doc/2
{
  "my_sparse_vector": {"2": 2.5, "10" : 1.3, "55": -2.3, "113": 1.6},
  "status" : "published"
}

POST my_sparse_index/_refresh</pre>
</div>
<div class="console_widget" data-snippet="snippets/267.console"></div>
<p>The <code class="literal">cosineSimilaritySparse</code> function calculates cosine similarity
between a given query vector and document vectors.</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">GET my_sparse_index/_search
{
  "query": {
    "script_score": {
      "query" : {
        "bool" : {
          "filter" : {
            "term" : {
              "status" : "published"
            }
          }
        }
      },
      "script": {
        "source": "cosineSimilaritySparse(params.query_vector, 'my_sparse_vector') + 1.0",
        "params": {
          "query_vector": {"2": 0.5, "10" : 111.3, "50": -1.3, "113": 14.8, "4545": 156.0}
        }
      }
    }
  }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/268.console"></div>
<p>The <code class="literal">dotProductSparse</code> function calculates dot product
between a given query vector and document vectors.</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">GET my_sparse_index/_search
{
  "query": {
    "script_score": {
      "query" : {
        "bool" : {
          "filter" : {
            "term" : {
              "status" : "published"
            }
          }
        }
      },
      "script": {
        "source": """
          double value = dotProductSparse(params.query_vector, 'my_sparse_vector');
          return sigmoid(1, Math.E, -value);
        """,
         "params": {
          "query_vector": {"2": 0.5, "10" : 111.3, "50": -1.3, "113": 14.8, "4545": 156.0}
        }
      }
    }
  }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/269.console"></div>
<p>The <code class="literal">l1normSparse</code> function calculates L<sup>1</sup> distance
between a given query vector and document vectors.</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">GET my_sparse_index/_search
{
  "query": {
    "script_score": {
      "query" : {
        "bool" : {
          "filter" : {
            "term" : {
              "status" : "published"
            }
          }
        }
      },
      "script": {
        "source": "1 / (1 + l1normSparse(params.queryVector, 'my_sparse_vector'))",
        "params": {
          "queryVector": {"2": 0.5, "10" : 111.3, "50": -1.3, "113": 14.8, "4545": 156.0}
        }
      }
    }
  }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/270.console"></div>
<p>The <code class="literal">l2normSparse</code> function calculates L<sup>2</sup> distance
between a given query vector and document vectors.</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">GET my_sparse_index/_search
{
  "query": {
    "script_score": {
      "query" : {
        "bool" : {
          "filter" : {
            "term" : {
              "status" : "published"
            }
          }
        }
      },
      "script": {
        "source": "1 / (1 + l2normSparse(params.queryVector, 'my_sparse_vector'))",
        "params": {
          "queryVector": {"2": 0.5, "10" : 111.3, "50": -1.3, "113": 14.8, "4545": 156.0}
        }
      }
    }
  }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/271.console"></div>
</div>

<div class="section">
<div class="titlepage"><div><div>
<h5 class="title">
<a id="score-explanation"></a>Explain request<a class="edit_me edit_me_private" rel="nofollow" title="Editing on GitHub is available to Elastic" href="https://github.com/elastic/elasticsearch/edit/7.7/docs/reference/query-dsl/script-score-query.asciidoc">edit</a>
</h5>
</div></div></div>
<p>Using an <a class="xref" href="search-explain.html" title="Explain API">explain request</a> provides an explanation of how the parts of a score were computed. The <code class="literal">script_score</code> query can add its own explanation by setting the <code class="literal">explanation</code> parameter:</p>
<div class="pre_wrapper lang-console">
<pre class="programlisting prettyprint lang-console">GET /twitter/_explain/0
{
    "query" : {
        "script_score" : {
            "query" : {
                "match": { "message": "elasticsearch" }
            },
            "script" : {
                "source" : """
                  long likes = doc['likes'].value;
                  double normalizedLikes = likes / 10;
                  if (explanation != null) {
                    explanation.set('normalized likes = likes / 10 = ' + likes + ' / 10 = ' + normalizedLikes);
                  }
                  return normalizedLikes;
                """
            }
        }
     }
}</pre>
</div>
<div class="console_widget" data-snippet="snippets/272.console"></div>
<p>Note that the <code class="literal">explanation</code> will be null when using in a normal <code class="literal">_search</code> request, so having a conditional guard is best practice.</p>
</div>

</div>

</div>

</div>
<div class="navfooter">
<span class="prev">
<a href="query-dsl-script-query.html">« Script query</a>
</span>
<span class="next">
<a href="query-dsl-wrapper-query.html">Wrapper query »</a>
</span>
</div>
</div>

                  <!-- end body -->
                </div>
                <div class="col-xs-12 col-sm-4 col-md-4" id="right_col">
                  <div id="rtpcontainer" style="display: block;">
                    <div class="mktg-promo">
                      <h3>Most Popular</h3>
                      <ul class="icons">
                        <li class="icon-elasticsearch-white"><a href="https://www.elastic.co/webinars/getting-started-elasticsearch?baymax=default&amp;elektra=docs&amp;storm=top-video">Get Started with Elasticsearch: Video</a></li>
                        <li class="icon-kibana-white"><a href="https://www.elastic.co/webinars/getting-started-kibana?baymax=default&amp;elektra=docs&amp;storm=top-video">Intro to Kibana: Video</a></li>
                        <li class="icon-logstash-white"><a href="https://www.elastic.co/webinars/introduction-elk-stack?baymax=default&amp;elektra=docs&amp;storm=top-video">ELK for Logs &amp; Metrics: Video</a></li>
                      </ul>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </section>

        </div>


<div id="elastic-footer"></div>
<script src="https://www.elastic.co/elastic-footer.js"></script>
<!-- Footer Section end-->

      </section>
    </div>

<script src="/guide/static/jquery.js"></script>
<script type="text/javascript" src="/guide/static/docs.js"></script>
<script type="text/javascript">
  window.initial_state = {}</script>
  </body>
</html>
